# encoding:utf-8
import requests


# 此处填写你在控制台-应用管理-创建应用后获取的AK(百度地图开放平台API)
ak = ""
params_ip = ""
location = ""
x = ""
y = ""
address = ""
ip_list = []
result_list = []
open_file = "./ip_inquire_address/crime_ip.txt"
output_file = "./ip_inquire_address/output_address.txt"

print("正在将ip地址解析为物理地址")

# 打开并读取文件（替换为你的 test.txt 实际路径，如 "C:/Users/xxx/test.txt" 或 "./test.txt"）
with open(open_file, "r", encoding="utf-8") as file:
    # 逐行读取，去除每行的换行符后添加到列表
    for line in file:
        ip = line.strip()  # strip() 用于去除换行符、空格等
        if ip:  # 避免空行
            ip_list.append(ip)

def chaxun_jinweidu():
    global location,x,y
    # 接口地址
    url = "https://api.map.baidu.com/location/ip"
    params = {
        "ip":  params_ip,
        "coor":    "bd09ll",
        "ak":       ak,

    }

    response = requests.get(url=url, params=params)
    dict_data = response.json()
    x = dict_data['content']['point']['x']
    y = dict_data['content']['point']['y']
    location = y + ',' + x
    print("正在获取经纬度~")

def chaxun_dizhi():
    global address
    # 接口地址
    url = "https://api.map.baidu.com/reverse_geocoding/v3/"
    params = {
        "ak": ak,
        "output": "json",
        "coordtype": "bd09ll",
        "extensions_poi": "1",
        "location": location,

    }
    response = requests.get(url=url, params=params)
    dict_data = response.json()
    address = dict_data['result']['formatted_address']
    print("正在获取地理位置~")


tmp = 1
for ip in ip_list:
    params_ip = ip
    chaxun_jinweidu()
    chaxun_dizhi()

    result_line = f"ip: {ip}  地址:{address}  经纬度:{location}\n"
    result_list.append(result_line)
    print(f"完成{ip}的位置解析")

# 循环结束后，一次性写入文件（覆盖原有内容）
with open(output_file, "w", encoding="utf-8") as f:
    f.writelines(result_list)

print(f"完成ip地址解析为物理地址，保存在{output_file}目录下的output_address.txt")
